<template>
    <div class="crm-expense-container">
        <el-dialog title="新增支出" v-model="isShowDialog" :close-on-click-modal="false">
            <el-form ref="addCrmExpenseFormRef" :model="formData" :rules="formRules" label-width="120px">
                <el-row :gutter="35">
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="关联合同" prop="contractId">
                            <el-select v-model="formData.contractId" filterable remote 
                                @change="handContractChange"
                                @click="loadContractData()"
                                :remote-method="loadContractData" placeholder="请选择关联合同" clearable class="w100">
								<el-option 
									v-for="item in contracts"
									:key="item.id"
									:label="`（${item.contractCode}）${item.contractName}`"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="支出主题" prop="expenseName">
                            <el-input v-model="formData.expenseName" placeholder="请输入支出主题" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="支出金额" prop="expenseAmount">
                            <el-input-number v-model="formData.expenseAmount" :min="0" placeholder="请输入支出金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="申请日期" prop="expenseTime">
                            <el-date-picker v-model="formData.expenseTime" placeholder="请输入申请日期" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12">
                        <el-form-item label="申请人" prop="ownerId">
                            <el-select v-model="formData.ownerId" filterable remote 
                                @change="handleOwnerChange"
                                @click="loadCrmUserData()"
                                :remote-method="loadCrmUserData" placeholder="请选择申请人" clearable class="w100">
								<el-option 
									v-for="item in owners"
									:key="item.id"
									:label="item.userName"
									:value="item.id">
								</el-option>
							</el-select>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="支出凭证" prop="attachments">
                            <Storage :model="attachment" @success="onUploadSuccess" @remove="onUploadRemove"></Storage>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="备注" prop="remark">
                            <el-input type="textarea" v-model="formData.remark" placeholder="请输入备注" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col>
                        <el-form-item label="是否开票" prop="hasInvoice">
                            <el-switch v-model="formData.hasInvoice" active-text="是" inactive-text="否"></el-switch>
                        </el-form-item>
                    </el-col>
                    <!-- 开票信息 -->
                    <el-col>
                        <el-form-item label="发票文件" prop="'invoice.attachments" v-if="formData.hasInvoice">
                            <Storage :model="invoice.attachment" @success="onUploadSuccess1" @remove="onUploadRemove1"></Storage>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="发票类型" prop="invoice.invoiceType">
                            <Dictionary v-model="formData.invoice.invoiceType" dict-label="crm_invoice_type" placeholder="请输入发票类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">

                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="发票代码" prop="invoice.invoiceCode">
                            <el-input v-model="formData.invoice.invoiceCode" placeholder="请输入发票代码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="发票号码" prop="invoice.invoiceNumber">
                            <el-input v-model="formData.invoice.invoiceNumber" placeholder="请输入发票号码" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="发票金额" prop="invoice.invoiceAmount">
                            <el-input-number v-model="formData.invoice.invoiceAmount" :min="0" placeholder="请输入发票金额（单位：元）" clearable class="w100"></el-input-number>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="开票日期" prop="invoice.invoiceDate">
                            <el-date-picker v-model="formData.invoice.invoiceDate" placeholder="请输入开票日期" value-format="YYYY-MM-DD" clearable class="w100"></el-date-picker>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="抬头类型" prop="invoice.invoiceTitleType">
                            <Dictionary v-model="formData.invoice.invoiceTitleType" dict-label="crm_invoice_title" placeholder="请输入抬头类型"></Dictionary>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="开票抬头" prop="invoice.invoiceTitle">
                            <el-input v-model="formData.invoice.invoiceTitle" placeholder="请输入开票抬头" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方纳税识别号" prop="invoice.buyerTaxNumber">
                            <el-input v-model="formData.invoice.buyerTaxNumber" placeholder="请输入购方纳税识别号" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="销方纳税识别号" prop="invoice.sellerTaxNumber">
                            <el-input v-model="formData.invoice.sellerTaxNumber" placeholder="请输入纳税识别号" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户行" prop="invoice.buyerDepositBank">
                            <el-input v-model="formData.invoice.buyerDepositBank" placeholder="请输入购方开户行" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="销方开户行" prop="invoice.sellerDepositBank">
                            <el-input v-model="formData.invoice.sellerDepositBank" placeholder="请输入销方开户行" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户账户" prop="invoice.buyerDepositAccount">
                            <el-input v-model="formData.invoice.buyerDepositAccount" placeholder="请输入购方开户账户" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="销方开户账户" prop="invoice.sellerDepositAccount">
                            <el-input v-model="formData.invoice.sellerDepositAccount" placeholder="请输入销方开户账户" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方开户地址" prop="invoice.buyerDepositAddress">
                            <el-input v-model="formData.invoice.buyerDepositAddress" placeholder="请输入购方开户地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="销方开户地址" prop="invoice.sellerDepositAddress">
                            <el-input v-model="formData.invoice.sellerDepositAddress" placeholder="请输入销方开户地址" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="购方联系电话" prop="invoice.buyerTelephone">
                            <el-input v-model="formData.invoice.buyerTelephone" placeholder="请输入购方联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" v-if="formData.hasInvoice">
                        <el-form-item label="销方联系电话" prop="invoice.sellerTelephone">
                            <el-input v-model="formData.invoice.sellerTelephone" placeholder="请输入销方联系电话" clearable></el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="onCancel">取 消</el-button>
                    <el-button type="primary" @click="onSubmit">保 存</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script lang="ts">
import { reactive, toRefs, ref } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { addCrmExpense } from '/@/api/crm/expense/index';
import { getCrmContractList } from '/@/api/crm/contract/index';
import { getCrmUserList } from '/@/api/crm/user/index';
import { getMyselContractList } from '/@/api/crm/mysel/index';
import Dictionary from '/@/components/dictionary/index.vue';
import Storage from '/@/views/crm/components/storage/index.vue';
export default {
    name: 'crm/expense/add',
    components: { Dictionary, Storage },
    setup(props, context) {
        const addCrmExpenseFormRef = ref();
        const validInvoiceAttachmentNotEmpty = (rule, value, callback) => {
            const { hasInvoice } = state.formData;
            const { attachments } = state.formData.invoice;
            if(hasInvoice && (attachments == undefined || attachments.length == 0)){
                return callback(new Error('发票文件不能为空'));
            }else{
                return callback();
            }
        }
        const state = reactive({
            isShowDialog: false,
            contracts: [],
            owners: [],
            attachment: {
                upload:{
                    limit: 5,
                    accept: '.jpg,.png,.svg,.webp,.gif,.pdf',
                    images: []
                }
            },
            invoice:{
                attachment: {
                    upload:{
                        limit: 1,
                        accept: '.jpg,.png,.svg,.webp,.gif,.pdf',
                        images: []
                    }
                },
            },
            formData: {
                attachments: [],
                hasInvoice: false,
                invoice: {
                    attachments: [],
                    invoiceType: '',
                    invoiceCode: '',
                    invoiceNumber: '',
                    invoiceAmount: 0,
                    invoiceDate: '',
                    invoiceTitleType: '',
                    invoiceTitle: '',
                    buyerTaxNumber: '',
                    sellerTaxNumber: '',
                    buyerDepositBank: '',
                    sellerDepositBank: '',
                    buyerDepositAccount: '',
                    sellerDepositAccount: '',
                    buyerDepositAddress: '',
                    sellerDepositAddress: '',
                    buyerTelephone: '',
                    sellerTelephone: '',
                },
            },
            formRules : {
                contractId: { required: true, message: '关联合同不能为空', trigger: 'blur' },
                expenseName: { required: true, message: '支出主题不能为空', trigger: 'blur' },
                expenseAmount: { required: true, message: '支出金额不能为空', trigger: 'blur' },
                expenseTime: { required: true, message: '申请日期不能为空', trigger: 'blur' },
                ownerId: { required: true, message: '申请人不能为空', trigger: 'blur' },
                'invoice.attachments': { required: true, validator: validInvoiceAttachmentNotEmpty, trigger: 'blur' },
                'invoice.invoiceType': { required: true, message: '发票类型不能为空', trigger: 'blur' },
                'invoice.invoiceAmount': { required: true, message: '发票金额不能为空', trigger: 'blur' },
                'invoice.invoiceDate': { required: true, message: '开票日期不能为空', trigger: 'blur' },
                'invoice.invoiceTitleType': { required: true, message: '抬头类型不能为空', trigger: 'blur' },
                'invoice.invoiceTitle': { required: true, message: '抬头不能为空', trigger: 'blur' },
            }
        });

        // 加载合同数据
        const loadContractData = async (query?: string) => {
            if(query == '') return;
            // 并行发起两个异步请求
            const [res1, res2] = await Promise.all([
                getCrmContractList({ contractCode: query, examineStatus: '2' }),
                getMyselContractList({ contractCode: query })
            ]);

            // 检查两个请求是否都成功
            if (res1.code !== 0 || res2.code !== 0) {
                return;
            }

            // 合并两个结果数组，并去重
            const combinedContracts = [...(res1.data || []), ...(res2.data || [])];

            // 使用 Map 来保证唯一性
            const uniqueContractsMap = new Map();
            combinedContracts.forEach(contract => {
                if (!uniqueContractsMap.has(contract.id)) {
                    uniqueContractsMap.set(contract.id, contract);
                }
            });

            // 更新 state.contracts 为最终的结果
            state.contracts = Array.from(uniqueContractsMap.values());
        };
        // 选择合同
        const handContractChange = (contractId) => {
            const contract = state.contracts.find(item => item.id == contractId);
            state.formData.contractId = contract?.id;
            state.formData.contractName = contract?.contractName;

            state.customers = [{id: contract?.customerId, customerName: contract?.customerName}];
            state.formData.customerId = contract?.customerId;
            state.formData.customerName = contract?.customerName;
        };

        const loadCrmUserData = (query?: string) => {
            if(query == '') return;
            getCrmUserList({userName: query}).then((res) => {
                if(res.code == 0){
                    state.owners = res.data;
                }
            });
        }
        const handleOwnerChange = (ownerId) => {
            const owner = state.owners.find(item => item.id == ownerId);
            state.formData.ownerId = owner?.id;
            state.formData.ownerName = owner?.userName;
        }

        const onUploadSuccess = (file, urls) => {
            state.formData?.attachments.push({url: file.url, name: file.name});
        };

        const onUploadRemove = (file, urls) => {
            const index = state.formData?.attachments.findIndex((item) => item.url == file.url);
            if(index > -1){
				state.formData?.attachments.splice(index, 1);
			}
        };

        const onUploadSuccess1 = (file, urls) => {
            state.formData?.invoice?.attachments.push({url: file.url, name: file.name});
        };

        const onUploadRemove1 = (file, urls) => {
            const index = state.formData?.invoice?.attachments.findIndex((item) => item.url == file.url);
            if(index > -1){
				state.formData?.invoice?.attachments.splice(index, 1);
			}
        };
        // 打开弹窗
        const openDialog = (row?: object) => {
            state.isShowDialog = true;
        };
        // 关闭弹窗
        const closeDialog = (row?: object) => {
            state.isShowDialog = false;
            for(var key in state.formData) {
                state.formData[key] = undefined;
            }
            addCrmExpenseFormRef.value.resetFields();
            state.formData.attachments = [];
            state.formData.invoice = {
                attachments: [],
                invoiceType: '',
                invoiceCode: '',
                invoiceNumber: '',
                invoiceAmount: 0,
                invoiceDate: '',
                invoiceTitleType: '',
                invoiceTitle: '',
                buyerTaxNumber: '',
                sellerTaxNumber: '',
                buyerDepositBank: '',
                sellerDepositBank: '',
                buyerDepositAccount: '',
                sellerDepositAccount: '',
                buyerDepositAddress: '',
                sellerDepositAddress: '',
                buyerTelephone: '',
                sellerTelephone: '',
            };
        };
        // 取消
        const onCancel = () => {
            closeDialog();
        };
        // 新增
        const onSubmit = () => {
            addCrmExpenseFormRef.value.validate(valid => {
                if(valid){
                    let params = {
                        contractId: state.formData.contractId,
                        contractName: state.formData.contractName,
                        expenseName: state.formData.expenseName,
                        expenseAmount: state.formData.expenseAmount,
                        expenseTime: state.formData.expenseTime,
                        ownerId: state.formData.ownerId,
                        ownerName: state.formData.ownerName,
                        remark: state.formData.remark,
                        attachments: state.formData.attachments,
                        hasInvoice: state.formData.hasInvoice,
                    }
                    if (state.formData.hasInvoice) {
                        params.invoice = state.formData.invoice;
                    }
                    addCrmExpense(params).then((res) => {
                        if(res.code === 0){
                            ElMessage.success('保存成功');
                            context.emit('submit');
                            closeDialog();
                        }
                    });
                }
            });
        };
        return {
            addCrmExpenseFormRef,
            openDialog,
            closeDialog,
            onCancel,
            onSubmit,
            loadContractData,
            handContractChange,
            loadCrmUserData,
            handleOwnerChange,
            onUploadSuccess,
            onUploadRemove,
            onUploadSuccess1,
            onUploadRemove1,
            ...toRefs(state),
        };
    },
};
</script>